using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Services;
using System.IdentityModel.Tokens.Jwt;
using UniversalAdmin.Shared.Enums;
using UniversalAdmin.Infrastructure.Data.Contexts;
using Microsoft.EntityFrameworkCore;

[ApiController]
[Route("api/auths")]
[AllowAnonymous]
public class AuthsController : ControllerBase
{
    private readonly IAppAuthServices _authServices;
    private readonly IAppJwtService _jwtService;
    private readonly IAppUserServices _userService;
    private readonly AdminDbContext _db;
    private readonly ILogger<AuthsController> _logger;

    public AuthsController(
        IAppAuthServices authServices, 
        IAppJwtService jwtService, 
        IAppUserServices userService,
        AdminDbContext db,
        ILogger<AuthsController> logger)
    {
        _authServices = authServices;
        _jwtService = jwtService;
        _userService = userService;
        _db = db;
        _logger = logger;
    }

    [AllowAnonymous]
    [HttpPost("register")]
    public async Task<IActionResult> Register(UserRegisterDto dto)
    {
        var res = await _authServices.RegisterAsync(dto.UserName, dto.Password, dto.Email);
        return Ok(res);
    }

    [AllowAnonymous]
    [HttpPost("Login")]
    public async Task<IActionResult> Login(UserLoginDto dto)
    {
        _logger.LogInformation("测试日志输出：用户尝试登录，用户名：{UserName}", dto.UserName);
        ApiResult res = await _authServices.LoginAsync(dto.UserName, dto.Password);
        return Ok(res);
    }

    [AllowAnonymous]
    [HttpPost("refresh")]
    public async Task<IActionResult> RefreshToken([FromBody] RefreshRequestDto request)
    {
        // 验证refreshToken
        var (isValid, token, userId, userName) = _jwtService.ValidateRefreshToken(request.RefreshToken);
        if (!isValid || userId == null)
        {
            return Ok(ApiResult.Failed((int)ApiStatusCode.UNAUTHORIZED, "refreshToken无效或已过期"));
        }

        // 生成新的token
        if (!Guid.TryParse(userId, out var userGuid))
        {
            return Ok(ApiResult.Failed((int)ApiStatusCode.UNAUTHORIZED, "refreshToken无效"));
        }

        var user = _db.AppUsers.FirstOrDefault(u => u.Id == userGuid);
        if (user == null)
        {
            return Ok(ApiResult.Failed((int)ApiStatusCode.UNAUTHORIZED, "用户不存在"));
        }

        var newAccessToken = _jwtService.GenerateAccessToken(user.Id, user.Username);
        var newRefreshToken = _jwtService.GenerateRefreshToken();

        var data = new Dictionary<string, object>
        {
            { "accessToken", newAccessToken },
            { "refreshToken", newRefreshToken }
        };

        return Ok(ApiResult.Success("Token刷新成功", data));
    }

    // 获取当前用户权限
    [HttpGet("permissions")]
    [Authorize]
    public async Task<ApiResult> GetCurrentUserPermissions()
    {
        try
        {
            // 获取当前用户ID
            var userIdClaim = User.FindFirst("UserId");
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                return ApiResult.Failed((int)ApiStatusCode.UNAUTHORIZED, "用户未登录");
            }

            // 获取用户权限
            var permissions = await _userService.GetUserPermissionsAsync(userId);
            
            return ApiResult.Success("获取用户权限成功", permissions);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户权限时发生错误: {ex.Message}");
        }
    }

    // 调试端点：检查用户权限状态
    [HttpGet("debug-permissions")]
    [Authorize]
    public async Task<ApiResult> DebugUserPermissions()
    {
        try
        {
            // 获取当前用户ID
            var userIdClaim = User.FindFirst("UserId");
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                return ApiResult.Failed((int)ApiStatusCode.UNAUTHORIZED, "用户未登录");
            }

            // 获取用户详细信息
            var user = await _db.AppUsers
                .Include(u => u.Roles)
                .ThenInclude(r => r.Permissions)
                .FirstOrDefaultAsync(u => u.Id == userId);

            if (user == null)
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");
            }

            // 构建调试信息
            var debugInfo = new
            {
                UserId = user.Id,
                UserName = user.Username,
                IsActive = user.IsActive,
                IsDelete = user.IsDelete,
                Roles = user.Roles.Select(r => new
                {
                    RoleId = r.Id,
                    RoleName = r.RoleName,
                    IsActive = r.IsActive,
                    IsDelete = r.IsDelete,
                    Permissions = r.Permissions.Select(p => new
                    {
                        PermissionId = p.Id,
                        PermissionCode = p.PermissionCode,
                        PermissionName = p.PermissionName,
                        IsActive = p.IsActive,
                        IsDelete = p.IsDelete
                    }).ToList()
                }).ToList(),
                AllPermissions = user.Roles
                    .Where(r => r.IsActive && !r.IsDelete)
                    .SelectMany(r => r.Permissions)
                    .Where(p => p.IsActive && !p.IsDelete)
                    .Select(p => p.PermissionCode)
                    .Distinct()
                    .ToList()
            };

            return ApiResult.Success("调试信息获取成功", debugInfo);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取调试信息时发生错误: {ex.Message}");
        }
    }
}